package com.linran.javaweb.executor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 专门有一个类来持有executor，这样bean销毁时，就能顺带销毁线程
 */
@Component
@Slf4j
public class CustomerExecutor implements DisposableBean {

    private final ThreadPoolExecutor executor;

    public CustomerExecutor() {
        //获取当先服务器可执行线程数
        int processors = Runtime.getRuntime().availableProcessors();
        executor = new ThreadPoolExecutor(processors / 2, processors / 2,
                1, TimeUnit.MINUTES,
                new LinkedBlockingQueue<>(5000), new ThreadPoolExecutor.DiscardPolicy());
    }

    public Future<?> submit(Runnable runnable) {
        return executor.submit(runnable);
    }

    @Override
    public void destroy() throws Exception {
        log.info("publish executor destroy");
        if (this.executor != null) {
            for (Runnable task : this.executor.shutdownNow()) {
                if (task instanceof Future) {
                    ((Future<?>) task).cancel(true);
                }
            }
            try {
                executor.awaitTermination(5000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
